package com.gzy.literature.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gzy.literature.dao.WorkCategoriesDao;
import com.gzy.literature.entity.WorkCategories;
import com.gzy.literature.service.WorkCategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;


@Service("WorkCategoriesService")
public class WorkCategoriesServiceImpl implements WorkCategoriesService {

    @Autowired
    private WorkCategoriesDao workCategoriesDao;

    @Override
    public WorkCategories queryById(Integer id) {
        // 校验ID是否为空
        if (id == null) {
            throw new IllegalArgumentException("ID不能为空");
        }
        return workCategoriesDao.queryById(id);
    }

    @Override
    public PageInfo<WorkCategories> queryGll(WorkCategories workCategories, int currentPage, int pageSize) {
        // 使用PageHelper进行分页查询
        PageHelper.startPage(currentPage, pageSize);
        List<WorkCategories> list = workCategoriesDao.queryGll(workCategories);
        // 封装分页结果
        PageInfo<WorkCategories> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public WorkCategories insert(WorkCategories workCategories) {
        // 校验插入对象是否为空以及必要字段是否填写
        if (workCategories == null || workCategories.getCategoryName() == null || workCategories.getCategoryName().trim().isEmpty()) {
            throw new IllegalArgumentException("插入对象或分类名称不能为空");
        }
        // 执行插入操作
        workCategoriesDao.insert(workCategories);
        // 插入后，由于使用了@Options(useGeneratedKeys = true, keyProperty = "id")，所以workCategories的id会被自动填充
        return workCategories;
    }

    @Override
    public WorkCategories update(WorkCategories workCategories) {
        // 校验更新对象是否为空以及必要字段是否填写
        if (workCategories == null || workCategories.getId() == null || workCategories.getCategoryName() == null || workCategories.getCategoryName().trim().isEmpty()) {
            throw new IllegalArgumentException("更新对象、ID或分类名称不能为空");
        }
        // 执行更新操作
        workCategoriesDao.update(workCategories);
        // 假设更新操作成功，返回更新后的对象（注意：这里假设数据库层已经处理了更新失败的情况）
        return workCategories;
    }

    @Override
    public boolean deleteById(Integer id) {
        // 校验ID是否为空
        if (id == null) {
            throw new IllegalArgumentException("ID不能为空");
        }
        // 执行删除操作并返回结果
        int affectedRows = workCategoriesDao.deleteById(id);
        return affectedRows > 0;
    }
}

